import promise from "es6-promise"
import "whatwg-fetch"
import { reject } from "rsvp";

let urlHead = "https://fo.huawanghaochen.com:8843"

var key = CryptoJS.enc.Utf8.parse("d7b85f6e214abcda");
function Encrypt(word) {
	var srcs = CryptoJS.enc.Utf8.parse(word);
	var encrypted = CryptoJS.AES.encrypt(srcs, key, {
		mode : CryptoJS.mode.ECB,
		padding : CryptoJS.pad.Pkcs7
	});
	return encrypted.toString();
}

function Decrypt(word) {
	var decrypt = CryptoJS.AES.decrypt(word, key, {
		mode : CryptoJS.mode.ECB,
		padding : CryptoJS.pad.Pkcs7
	});
	return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}


function xhrRett(url,params={},type="POST") {
	return new Promise((resolve, reject)=>{

		let xhr = new XMLHttpRequest()
		xhr.open(type, url, true);
		xhr.onload = function (e) {
			if (xhr.readyState === 4) {
				if (xhr.status === 200) {
					resolve(xhr.responseText)
				} else {
					reject(xhr.statusText)
				}
			}
		};

		xhr.onerror = function (e) {
			reject(xhr.statusText)
		};

		xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8");
		xhr.send(Encrypt(JSON.stringify(params)));
	})
}

export const getResponse = async (url, token) => {
	const response = await xhrRett(urlHead+url, {
		method: "POST",
		headers: {
			"Content-Type": "application/json;charset=utf-8",
			'token': token || ''
		}
	}).catch((error) => {
		console.log(error)
	})

	try{
		var jsonp = await response.json()
		if(jsonp.code === 1003 || jsonp.code === 1004) {
			window.location="/"
			return;
		} 

		return jsonp
	}catch(error) {
		console.log(error)
	}

}

export const getResponses = async (url, params) => {
	const response = await xhrRett(urlHead+url, params)

	return JSON.parse(JSON.parse(Decrypt(response)))
	// console.log()

	// try{
	// 	var jsonp = await response.json()
	// 	if(jsonp.code === 1003 || jsonp.code === 1004) {
	// 		window.location="/"
	// 		return;
	// 	} 
	// 	return jsonp
	// }catch(error) {
	// 	console.log(error)
	// }
}

export const getResponsesFile = async (url, params) => {
	const response = await fetch(urlHead+url, {
		method: "POST",
		body: params
	}).catch((error) => {
		console.log(error)
	})

	return await response.json().catch((error) => {
		console.log(error)
	})
}
